/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.tmq.diancan.service.impl;

import com.tmq.diancan.dto.CartDTO;
import com.tmq.diancan.entity.DiancanProductInfo;
import com.tmq.diancan.enums.ResultEnum;
import com.tmq.diancan.exception.ServiceException;
import com.tmq.diancan.vo.DiancanProductInfoVO;
import com.tmq.diancan.mapper.DiancanProductInfoMapper;
import com.tmq.diancan.service.IDiancanProductInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.sf.ehcache.util.ProductInfo;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品表 服务实现类
 *
 * @author tangmqb
 * @since 2020-01-10
 */
@Service
public class DiancanProductInfoServiceImpl extends ServiceImpl<DiancanProductInfoMapper, DiancanProductInfo> implements IDiancanProductInfoService {

	@Override
	public IPage<DiancanProductInfoVO> selectDiancanProductInfoPage(IPage<DiancanProductInfoVO> page, DiancanProductInfoVO diancanProductInfo) {
		return page.setRecords(baseMapper.selectDiancanProductInfoPage(page, diancanProductInfo));
	}

	@Override
	@Transactional(rollbackFor = ServiceException.class)
	public void decreaseStock(List<CartDTO> cartDTOList) {
		for (CartDTO cartDTO: cartDTOList) {
			DiancanProductInfo productInfo =baseMapper.selectById(cartDTO.getProductId());
			if (productInfo == null) {
				throw new ServiceException(ResultEnum.PRODUCT_NOT_EXIST.getMessage());
			}
			Integer result = productInfo.getProductStock() - cartDTO.getProductQuantity();
			if (result < 0) {
				throw new ServiceException(ResultEnum.PRODUCT_STOCK_ERROR.getMessage());
			}

			productInfo.setProductStock(result);

			baseMapper.updateById(productInfo);
		}
	}
}
